/* eslint-disable no-case-declarations */
import React, { useState, useEffect } from 'react';
import { Button, Form as FormAntd, Input, InputNumber, Radio, message } from 'antd';
import dayjs from 'dayjs';
import { model } from '@/ts/base';
import { schema } from '@/ts/base';
import { ValueType } from '@/ts/core/public/enums';
import orgCtrl from '@/ts/controller';
import FullScreenModal from '@/components/Common/fullScreen';

interface Iprops {
  things: schema.XThing[];
  printConfig: { [key: string]: string }; // 打印模板配置
  qrcodeConfig: { label: string; value: string; type: string }[];
  fields: model.FieldModel[];
  finished: () => void;
}

const mmlist = [
  { dpi: 203, value: 8 },
  { dpi: 300, value: 12 },
  { dpi: 600, value: 24 },
];
export const PoskPrint: React.FC<Iprops> = ({
  things,
  printConfig,
  qrcodeConfig,
  fields,
  finished,
}) => {
  let ConnectionType: string = 'usb';
  let card;
  const [connectionType, setConnectionType] = useState<string>(ConnectionType);
  const [printForm, setPrintForm] = useState({
    usbport: '255',
    ipadd: '',
    ipport: '',
    dpi: 300,
    label: {
      height: printConfig.height,
      width: printConfig.width,
      gap: 0,
    },
    text: {
      height: printConfig.fontSize,
    },
    topblank: 2,
  });
  const handleRadioChange = (e: any) => {
    const value = e.target.value;
    setConnectionType(value);
    ConnectionType = value; // 同步更新全局变量（如果其他地方有依赖）
  };
  const decimalToHex = (decimalStr: string): string => {
    let hex = BigInt(decimalStr).toString(16).toUpperCase();
    // 补零逻辑：若长度为奇数，在左侧补零（保持数值正确性）
    return hex.length % 2 === 0 ? hex : '0' + hex;
  };
  const PrintContent = () => {
    const mm = mmlist.find((item) => item.dpi === printForm.dpi)?.value;
    const QRv = 3;
    const QRR = 5;
    const QRL = QRR * (21 + 4 * (QRv - 1));
    if (mm != undefined) {
      const forntsize = Math.round(printForm.text.height * 0.35 * mm);
      window.PTK_ClearBuffer();
      window.PTK_SetDarkness(10);
      window.PTK_SetPrintSpeed(4);
      window.PTK_SetDirection('T');
      window.PTK_SetRFID(0, 0, 0, 0, 0);
      window.PTK_SetLabelHeight(
        printForm.label.height * mm,
        printForm.label.gap * mm,
        0,
        false,
      );
      window.PTK_SetLabelWidth(printForm.label.width * mm);
      for (let i = 0; i < card.length; i++) {
        window.PTK_DrawBar2D_QR(
          printForm.topblank * mm, //x
          printForm.topblank * mm, //y
          0, //w
          0, //v
          0, //o
          QRR, //r
          0, //m
          0, //g
          8, //s
          card[i][0].id.toString(),
        );
        let id = decimalToHex(card[i][0].id);
        window.PTK_RWRFIDLabel(1, 0, 2, id.length / 2, 1, id);
        for (let j = 0; j < card[i].length; j++) {
          const { field, value } = card[i][j];
          const text = `${field}:${value}`;
          window.PTK_DrawText_TrueType(
            QRL + printForm.topblank * mm + mm, //x
            printForm.topblank * mm + j * forntsize + mm / 2, //y
            forntsize,
            0,
            'Arial',
            1,
            400,
            0,
            0,
            0,
            text,
          );
        }
        window.PTK_PrintLabel(1, 1);
      }
    } else {
      message.warn('打印机分辨率设置错误');
    }
  };

  // useEffect(() => {
  //   if (open) {
  //     handleBefore();
  //   }
  // }, [open]);
  /** 打印之前 */
  const handleBefore = () => {
    card = things.map((thing) => {
      return qrcodeConfig.map((i) => {
        let res = thing[i.value];
        let data = fieldMapping(i, res);
        return { field: i.label, value: data, id: thing[printConfig?.qrcodeSource] };
      });
    });
  };

  /** 执行打印程序 */
  const handlePrint = () => {
    handleBefore();
    switch (connectionType) {
      case 'usb':
        window.PTK_OpenUSBPort(printForm.usbport);
        //window.PTK_RFIDCalibrate();
        PrintContent();
        window.PTK_CloseUSBPort();
        printing();
        break;
      case 'net':
        window.PTK_Connect_Timer(printForm.ipadd, printForm.ipport, 5);
        //window.PTK_RFIDCalibrate();
        PrintContent();
        window.PTK_CloseConnect();
        printing();
        break;
    }
  };

  // 打印函数
  const printing = () => {
    const data = {
      reqParam: '1',
      printparams: JSON.stringify(window.printparamsJsonArray),
    };
    window.clean();
    fetch('http://127.0.0.1:888/postek/print', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
      timeout: 5000,
    })
      .then((response) => response.json())
      .then((result) => {
        if (result.retval === '0') {
          console.log('运行成功！');
        } else {
          console.log(`存在错误，返回结果：${result.msg}`);
        }
      })
      .catch((error) => {
        console.log('请求失败，请检查参数是否正确或服务是否开启');
      });
  };

  /** 字段映射 */
  const fieldMapping = (
    config: { label: string; value: string; type: string },
    item: string,
  ) => {
    switch (config.type) {
      case ValueType.Remark:
      case ValueType.Number:
        return item || '--';
      case '':
      case ValueType.File:
      case ValueType.Reference:
      case ValueType.Object:
        return '--';
      case ValueType.Date:
        return dayjs(item).format('YYYY-MM-DD') || '--';
      case ValueType.Time:
        return dayjs(item).format('HH:mm:ss') || '--';
      case ValueType.Species:
      case ValueType.Select:
        const curField = fields.find((field) => field.id === config.value);
        if (curField) {
          return curField.lookups?.find((itea) => itea.value === item)?.text || '--';
        } else {
          return '--';
        }
      case ValueType.Target:
        return orgCtrl.user.findShareById(item).name || '--';
      default:
        return '--';
    }
  };

  return (
    <FullScreenModal
      open
      title={'RFID标签打印'}
      width={'360px'}
      bodyHeight={'360px'}
      footer={
        <Button
          type="primary"
          onClick={() => {
            handlePrint();
            finished();
          }}>
          打印
        </Button>
      }
      onCancel={() => finished()}>
      <div>
        <Radio.Group defaultValue={ConnectionType} onChange={handleRadioChange}>
          <Radio value="usb">USB打印</Radio>
          <Radio value="net">网络打印</Radio>
        </Radio.Group>
        <FormAntd layout="vertical">
          <FormAntd.Item label="USB端口">
            <Input
              defaultValue={printForm.usbport}
              onChange={(e) => {
                if (e.target.value) {
                  setPrintForm((prev) => ({
                    ...prev,
                    usbport: e.target.value,
                  }));
                }
              }}
              disabled={connectionType !== 'usb'}
            />
          </FormAntd.Item>
          <FormAntd.Item label="打印机IP地址">
            <Input
              defaultValue={printForm.ipadd}
              onChange={(e) => {
                if (e.target.value) {
                  setPrintForm((prev) => ({
                    ...prev,
                    ipadd: e.target.value,
                  }));
                }
              }}
              disabled={connectionType !== 'net'}
            />
          </FormAntd.Item>
          <FormAntd.Item label="打印机IP端口">
            <Input
              defaultValue={printForm.ipport}
              onChange={(e) => {
                if (e.target.value) {
                  setPrintForm((prev) => ({
                    ...prev,
                    ipport: e.target.value,
                  }));
                }
              }}
              disabled={connectionType !== 'net'}
            />
          </FormAntd.Item>
          <FormAntd.Item label="打印机分辨率">
            <Input
              defaultValue={printForm.dpi}
              onChange={(e) => {
                if (e.target.value) {
                  setPrintForm((prev) => ({
                    ...prev,
                    dpi: Number(e.target.value),
                  }));
                }
              }}
            />
          </FormAntd.Item>
          <FormAntd.Item label="标签高度(mm)">
            <InputNumber
              defaultValue={printForm.label.height}
              onChange={(e) => {
                const value = e;
                if (value) {
                  setPrintForm((prev) => ({
                    ...prev,
                    label: {
                      ...prev.label,
                      height: Number(value),
                    },
                  }));
                }
              }}
            />
          </FormAntd.Item>
          <FormAntd.Item label="标签宽度(mm)">
            <InputNumber
              defaultValue={printForm.label.width}
              onChange={(e) => {
                const value = e;
                if (value) {
                  setPrintForm((prev) => ({
                    ...prev,
                    label: {
                      ...prev.label,
                      width: Number(value),
                    },
                  }));
                }
              }}
            />
          </FormAntd.Item>
          <FormAntd.Item label="标签间隙(mm)">
            <InputNumber
              defaultValue={printForm.label.gap}
              onChange={(e) => {
                const value = e;
                if (value) {
                  setPrintForm((prev) => ({
                    ...prev,
                    label: {
                      ...prev.label,
                      gap: Number(value),
                    },
                  }));
                }
              }}
            />
          </FormAntd.Item>
          <FormAntd.Item label="字体大小(pt)">
            <InputNumber
              defaultValue={printForm.text.height}
              onChange={(e) => {
                const value = e;
                if (value) {
                  setPrintForm((prev) => ({
                    ...prev,
                    text: {
                      ...prev.text,
                      height: Number(value),
                    },
                  }));
                }
              }}
            />
          </FormAntd.Item>
          <FormAntd.Item label="距离顶部距离(mm)">
            <InputNumber
              defaultValue={printForm.topblank}
              onChange={(e) => {
                const value = e;
                if (value) {
                  setPrintForm((prev) => ({
                    ...prev,
                    topblank: Number(value),
                  }));
                }
              }}
            />
          </FormAntd.Item>
        </FormAntd>
      </div>
    </FullScreenModal>
  );
};
